/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package pessoas.presenter;

import daobase.DaoAbstractFactory;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import pessoas.log.ConfiguracoesLog;
import pessoas.manipulaJar.LeitorJar;
import pessoas.model.Contato;
import pessoas.dao.FacadeDao;
import pessoas.view.ConfiguracoesView;
import txtdao.FabricaTxtConcreta;
import xmldao.FabricaXmlConcreta;

/**
 *
 * @author Bush
 */
public class ConfiguracoesPresenter {

    private ConfiguracoesView view;
    private ConfiguracoesLog configLog;

    public ConfiguracoesPresenter() {
        view = new ConfiguracoesView(null, true);
        exibeLogs();
        try {
            atualizaTipo();
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        } catch (ClassNotFoundException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        } catch (InstantiationException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        } catch (IllegalAccessException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
        view.getBtnAlterar().addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    alterar();
                } catch (ClassNotFoundException ex) {
                    JOptionPane.showMessageDialog(null, ex.getMessage());
                } catch (InstantiationException ex) {
                    JOptionPane.showMessageDialog(null, ex.getMessage());
                } catch (IllegalAccessException ex) {
                    JOptionPane.showMessageDialog(null, ex.getMessage());
                }
            }
        });

        view.getBtnFechar().addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                view.dispose();
            }
        });
        try {
            inicializaPlugins();
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        } catch (ClassNotFoundException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
        view.setLocationRelativeTo(view);
        view.setVisible(true);
    }

    public void exibeLogs() {
        try {
            ArrayList<Object> lista = ConfiguracoesLog.getInstancia().listaTiposLog();
            for (int i = 0; i < lista.size(); i++) {
                view.getComboTipo().addItem(lista.get(i));
            }
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        } catch (ClassNotFoundException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        } catch (InstantiationException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        } catch (IllegalAccessException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
    }

    public void atualizaTipo() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {
        try {
            view.getTxtTipoAtual().setText(ConfiguracoesLog.getInstancia().getTipoLog());
        } catch (FileNotFoundException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
    }

    public void alterar() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        try {
            ConfiguracoesLog.getInstancia().alteraTipoLog(view.getComboTipo().getSelectedItem().toString());
            alterarDao();
            JOptionPane.showMessageDialog(null, "Alterado com Sucesso!!");
            atualizaTipo();
        } catch (FileNotFoundException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
    }

    public void alterarDao() {
        try {
            ArrayList<Contato> c = FacadeDao.getInstancia().lerContatos();
            ArrayList<Contato> i = FacadeDao.getInstancia().lerContatosInvalido();
            if (view.getComboPersistencia().getSelectedItem().equals("Serialização Txt")) {
                FacadeDao.getInstancia().setDao(new FabricaTxtConcreta(), c, i);
            } else if (view.getComboPersistencia().getSelectedItem().equals("Serialização Xml")) {
                FacadeDao.getInstancia().setDao(new FabricaXmlConcreta(), c, i);
            }
//            instanciaFabricaDao(view.getComboPersistencia().getSelectedItem().toString(), c, i); // Método para instanciar de forma dinânmica a Dao
        } catch (FileNotFoundException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
    }

    ;
    
     public void inicializaPlugins() throws IOException, ClassNotFoundException {
        configPluginCombo();
    }

    private void configPluginCombo() throws MalformedURLException, IOException, ClassNotFoundException {
        LeitorJar leitor = new LeitorJar(new File("").getAbsolutePath() + "/src/pessoas/plugins");
        Map<String, Map.Entry<String, URL>> classesPlugin = leitor.getClassesPlugin();

        for (Map.Entry<String, Map.Entry<String, URL>> entry : classesPlugin.entrySet()) {
            String nomeMenu = entry.getKey();
            Map.Entry<String, URL> classe = entry.getValue();
            view.getComboPersistencia().addItem(nomeMenu);
        }
    }

    private void instanciaFabricaDao(String dao, ArrayList<Contato> c, ArrayList<Contato> i) throws MalformedURLException, IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {
        LeitorJar leitor = new LeitorJar(new File("").getAbsolutePath() + "/src/pessoas/plugins");
        Map<String, Map.Entry<String, URL>> classesPlugin = leitor.getClassesPlugin();

        for (Map.Entry<String, Map.Entry<String, URL>> entry : classesPlugin.entrySet()) {
            String nomeMenu = entry.getKey();
            Map.Entry<String, URL> classe = entry.getValue();
            String endClasse = "pessoas.plugins."+classe.getKey();
            Class novaClasse = Class.forName(endClasse); // Não consegui pegar o caminho do projeto até o jar que fosse possivel criar uma classe apartir dele
            Object o = novaClasse.newInstance();
            DaoAbstractFactory fabrica = (DaoAbstractFactory) o;
            if (dao.equals(nomeMenu)) {
                FacadeDao.getInstancia().setDao(fabrica, c, i);
            }
        }
    }

}
